package rwt.controlpanel;

import java.io.*;
import java.util.Properties;

/**
 * Persistent preferences for controlling how the web server is run (install paths, show command window, etc.).
 */
public class Preferences
{
	public static final String PREFS_FILE = Constants.CONFIG_DIR_PATH + "/control-panel-prefs.properties";
	public static final String KEY_LAST_CONFIG = "LastConfig";
	public static final String KEY_JDK_PATH = "JdkPath";
	public static final String KEY_GNAT_AJIS_PATH = "GnatAjisPath";
	public static final String KEY_SHOW_COMMAND_WINDOW = "ShowCommandWindow";
	
	private static boolean loaded = false;
	private static Properties props = new Properties();
	
	private static synchronized void load()
	{
		if (loaded)
			return;
		loaded = true;
		
		File prefsFile = new File(PREFS_FILE);
		if (prefsFile.isFile())
		{
			try
			{
				props.load(new FileReader(prefsFile));
			}
			catch (IOException e)
			{
				e.printStackTrace();
			}
		}
	}
	
	public static String getLastConfig()
	{
		if (!loaded)
			load();
		return props.getProperty(KEY_LAST_CONFIG);
	}
	
	public static void setLastConfig(String value)
	{
		if (!loaded)
			load();
		props.setProperty(KEY_LAST_CONFIG, value);
	}
	
	public static String getJdkPath()
	{
		if (!loaded)
			load();
		return props.getProperty(KEY_JDK_PATH, System.getenv("JAVA_HOME"));
	}
	
	public static void setJdkPath(String value)
	{
		if (!loaded)
			load();
		props.setProperty(KEY_JDK_PATH, value);
	}

	public static String getGnatAjisPath()
	{
		if (!loaded)
			load();
		return props.getProperty(KEY_GNAT_AJIS_PATH);
	}
	
	public static void setGnatAjisPath(String value)
	{
		if (!loaded)
			load();
		props.setProperty(KEY_GNAT_AJIS_PATH, value);
	}
	
	public static boolean getShowCommandWindow()
	{
		if (!loaded)
			load();
		return Boolean.parseBoolean(props.getProperty(KEY_SHOW_COMMAND_WINDOW, "false"));
	}
	
	public static void setShowCommandWindow(boolean value)
	{
		if (!loaded)
			load();
		props.setProperty(KEY_SHOW_COMMAND_WINDOW, Boolean.toString(value));
	}
	
	public static void save()
	{
		try (FileOutputStream fos = new FileOutputStream(PREFS_FILE))
		{
			props.store(fos, "Preferences for the RWT Control Panel.");
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}
}
